<?php

/**
 * 贵阳仓保税自提 SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopguiyang;
use App\Model\PssModel\ServiceConfig;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use Hyperf\Utils\WaitGroup;

class ShopguiyangApiClient
{
    private $account  = 'Shopguiyang';
    protected $config;
    protected $RouteMap = [
        'createOrder'           => '/merchant/createOrder',
        'queryGoods'            => '/merchantInventory/query',
        'queryGoodsDetail'      => '/merchantInventory/search',
        'queryOrderExpress'     => '/merchant/customsStatus',
    ];
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //商品下单组
        $Items = [];
        $productAmt = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item ) 
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);
            //单个商品总不含税价格
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount,2);
            //商品组
            $Items[] = [
                "UPCNo"            => $item['supplier_skucode'],
                "ProductQty"       => $buyAcount,
                "UnitPrice"        => $singleGoodsPrice,
                "SubTotalAmount"   => $totalGoods,
                "SubTaxAmount"     => 0,
            ];
            $productAmt = bcadd((string)$productAmt,(string)$totalGoods,2);
        }
        //实际下单金额 
        $real_total_money = $orderInfo['real_total_money'];
        //订单总金额 = 不含税商品总金额 + 总税费 + 运费 - 优惠金额
        $ActualPaidAmt = bcadd((string)$productAmt,(string)$TaxAmt,2);
        $ActualPaidAmt = bcadd((string)$ActualPaidAmt,(string)$deliver_money,2);
        //优惠金额
        $discount_money = bcsub((string)$ActualPaidAmt,$real_total_money,2);
        //支付时间
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('Y-m-d H:i:s',$pay_time);
        //支付流水号
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        } 
        //电商平台信息
        $enterpriseNum  = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum  = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        //物流信息
        $logisticCode = !empty($apply_extends['logisticCode']) ? $apply_extends['logisticCode'] : $order['logisticCode'];
        $logisticNo   = !empty($apply_extends['logisticNo']) ? $apply_extends['logisticNo'] : $order['logisticNo'];
        
        $express_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_BILL_WAY, $logisticCode);
        if (empty($express_value)) {
            return Normal::returnCode(Normal::FAIL, "物流公司编码：【{$logisticCode}】未映射，请联系管理员处理");
        }
        //创建订单数据
        $order = [
            'OriginOrderNo'         => $orderInfo['supplier_dsn'],
            'SaleOrderTime'         => date("Y-m-d H:i:s",time()),
            'SalesOrderType'        => 1,
            'InvoicingCurrency'     => "CNY",
            'AcceptedExRate'        => 1,
            'PaymentTime'           => $pay_time,
            'OrderSource'           => 'other',
            'PaymentStatus'         => 1,
            'PaymentType'           => $pay_value,
            'SaleOrderPaymentNo'    => $pay_sn,
            'ShopNo'                => $this->config["ShopNo"],
            'ConsigneeCountry'      => "中国",
            'ConsigneeProvince'     => $orderInfo['province'],
            'ConsigneeCity'         => $orderInfo['city'],
            'ConsigneeDistrict'     => $orderInfo['district'],
            'ConsigneeStreetLine'   => $orderInfo['receive_address'],
            'Consignee'             => $orderInfo['receive_name'],
            'ConsigneePhone'        => $orderInfo['recveive_phone'],
            'BuyerName'             => $orderInfo['buyer_realname'],
            'BuyerIdNumber'         => $orderInfo['buyer_idcard'],
            'CourierNo'             => $express_value,
            'TrackingNo'            => $logisticNo,
        ];
        $data = [
            'order'     => $order,
            'Items'     => $Items,
            'FeeItems'  => [
                [
                    'FeeFieldName' => "DiscountAmount",
                    'FeeAmount'    => $discount_money ? "-".$discount_money : $discount_money,
                ],
                [
                    'FeeFieldName' => "ShippingPrice",
                    'FeeAmount'    => $deliver_money
                ],
                [
                    'FeeFieldName' => "ProductTax",
                    'FeeAmount'    => $TaxAmt
                ],
            ],
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        $res = $this->execute($requestParam);
        if( $res['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $res["data"]["Result"]['SalesOrderNo']
            ]);
        }
        return $res;
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        return Normal::returnCode(Normal::SUC,"处理成功");
    }
    
    /**
     * 查询物流单信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $data = [
            'ErpCodes'  => [
                [
                    'SalesCode'    => $param['thirdpart_order_sn']
                ]
            ]
        ];
        $requestParam = [
            'method'    => 'queryOrderExpress',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 根据SkuCode获取商品库存
     */
    public function queryGoodsListBySkuNo()
    {
        return $this->queryGoodsDetail();
    }
    
    /**
     * 查询商品详情
     */
    public function queryGoodsDetail()
    {
        $data = [
            'WarehouseNo' => $this->config["WarehouseNo"]
        ];
        $requestParam = [
            'method'    => 'queryGoods',
            'data'      => $data,
        ];
        $res        = $this->execute($requestParam);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $result_query_goods = $res["data"]["Result"];
        $details    = [];
        $size       = $this->config['limit'] ?? 10;
        $chunkArr   = array_chunk($result_query_goods,$size);
        foreach ($chunkArr as $skuNos) 
        {            
            $wg = new WaitGroup();
            $count = count($skuNos);
            $wg->add($count);
            foreach ($skuNos as $sku)
            {
                co(function () use ($wg,$sku, & $details) 
                {
                    $data = [
                        'StockQuery'  => [
                            [
                                'UPCNo'          => $sku["UPCNo"],
                            ]
                        ],
                        'WarehouseNo' => $this->config["WarehouseNo"],
                        'Page' => 1,
                        'Rows' => 1,
                    ];
                    $requestParam = [
                        'method'    => 'queryGoodsDetail',
                        'data'      => $data,
                    ];
                    $responseParam = $this->execute($requestParam);
                    if ($responseParam['code']== Normal::SUC && isset($responseParam['data']['Result'])){
                        $details[]=$responseParam['data'];
                    }
                    $wg->done();
                });
            }
            $wg->wait();
        }        
        return $details;
    }
    
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( $params = [] )
    {
        //第一步：组装参数("POST" + apiHost + apiName + secretKey + timestamp)
        $string="post".$params["baseurl"].$params["method"].$params["secretKey"].$params["timestamp"];
        //第二步：将组装完的字符串转成小写
        $string=strtolower($string);
        //第三步：md5
        $string=md5($string);
        //第四步：md5转大写
        return strtoupper($string);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }

        $baseurl=$this->config["baseurl"];
        $method = $param['method'];
        $appKey=$this->config["appKey"];
        $secretKey=$this->config["secretKey"];
        $timestamp=time();

        $signArr=[
            'baseurl'   => $baseurl,
            'method'    => $this->RouteMap[$method],
            'secretKey' => $secretKey,
            'timestamp' => $timestamp,
        ];
        
        $sign=$this->getSign($signArr);
        $url = $baseurl.$this->RouteMap[$method]."?appKey=".$appKey."&sign=".$sign."&timestamp=".$timestamp;
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => ["Content-Type: application/json; charset=utf-8"],
        
            ],
        ];
        if( in_array($method,['queryGoods','queryGoodsDetail']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['Success']) && $resHttp['Success'] == 1 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        
        $message = isset($resHttp['Message']) ? $resHttp['Message'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}